// pages/me/me.js
const app = getApp()
const defaultAvatarUrl = '/images/user.png'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,
    show: false,
    avatarUrl: defaultAvatarUrl,
    nickName: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.refreshData()
  },
  showPopup() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },
  toOrderList(e){
    let active = e.currentTarget.dataset.active
    wx.navigateTo({
      url: './orderList/orderList?active=' + active,
    })
  },
  login(){
   if(this.data.userInfo){
    this.setData({
      hasUserInfo: true
    })
    return
   }
   this.setData({
     show: true
   })
  },
  outLogin(){
    this.setData({
      hasUserInfo: false,
      //userInfo: ''
    })
  },
  attent(){
    wx.navigateTo({
      url: './attent/attent',
    })
  },
  onShareAppMessage(res){
    let myObj = {
      title:'琪琪的手工饰品屋',
      path:"/pages/me/me",
    }
    return myObj;
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    console.log(e.detail)
    this.setData({
      avatarUrl,
    })
  },
  submit(e){
    let that = this
    if(!this.data.nickName){
      wx.showToast({
        title: '还没输入用户名',
      })
      return
    } 
    wx.cloud.uploadFile({
      cloudPath: this.data.nickName + this.data.avatarUrl.substring(this.data.avatarUrl.lastIndexOf(".")),
      filePath: this.data.avatarUrl,
      success: res => {
        // get resource ID
        // console.log(res.fileID)
        let user = {
          user_nickname: that.data.nickName,
          user_photo: res.fileID,
          user_regtime: new Date()
        }
        //同时存到本地
        wx.setStorageSync('userInfo', user)
        //console.log(user)
        const db = wx.cloud.database()
        db.collection('users').add({
          data: user
        }).then(res =>{
          user._id = res._id
          app.globalData.cur_user = user
          this.refreshData()
          that.setData({
            show: false
          })
        })
      },
      fail: err => {
        // handle error
        console.log(err)
      }
    })
  },
  refreshData(){
    let that = this
    this.setData({
      userInfo: app.globalData.cur_user
    })
    // console.log(this.data.userInfo)
    let inter = this.data.userInfo
    // 定期检查flag的值
    var intervalId = setInterval(function () {
      if (inter) {
        that.setData({
          hasUserInfo: true
        })
        // 在需要时关闭定时器
        clearInterval(intervalId)
      }
    }, 1000)
  }
})